﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ShareMarking.Systems.Service;
using ShareMarking.Service;
using ShareMarking.Entity;
using System.Data;
using Common.Utilities.Excel.Export;
using System.IO;
using MySoft.Data;
using Common.Utilities.Excel;

namespace ShareMarking.Web.admin.EnterPrise.Employee
{
    public partial class PA : ManagePage
    {
        #region 参数配置=================================

        protected int totalCount;
        protected int page;
        protected string EmployeeNumber__c = string.Empty;
        protected string Region__c = string.Empty;
        protected string Area__c = string.Empty;
        protected string Name__c = string.Empty;
        protected string IsActive__c = string.Empty;
   
        protected string pageSizeCookieKey = "sfdc_PNR_index_page_size";//当前页的每页大小的cookiekey
        protected int pageSize
        {
            get
            {
                int _default_size = 10;
                int _pagesize;
                if (int.TryParse(Utils.GetCookie(pageSizeCookieKey), out _pagesize))
                {
                    if (_pagesize > 0)
                    {
                        return _pagesize;
                    }
                }
                return _default_size;
            }
        }
        protected string orderBy = "sfdc_PNR.PNRID desc";

        protected string keywords = string.Empty;
        protected string searchURL { 
            get 
            { return Utils.CombUrlTxt("PA.aspx", "EmployeeNumber__c={0}&Region__c={1}&Area__c={2}&Name__c={3}&IsActive__c={4}", 
                this.EmployeeNumber__c, this.Region__c, this.Area__c, this.Name__c,this.IsActive__c); 
            }
        }

        #endregion

        #region 初始化===================================

        protected void Page_Load(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.View.ToString());

            //初始化搜索参数
            this.keywords = DTRequest.GetQueryString("keywords");
            this.EmployeeNumber__c = DTRequest.GetQueryString("EmployeeNumber__c");
            this.Region__c = DTRequest.GetQueryString("Region__c");
            this.Area__c = DTRequest.GetQueryString("Area__c");
            this.Name__c = DTRequest.GetQueryString("Name__c");
            this.IsActive__c = DTRequest.GetQueryString("IsActive__c");
            if (!Page.IsPostBack)
            {
                //绑定下拉框的值

                //绑定列表
                RptBind();
            }
        }

        #endregion

        #region 绑定下拉框===============================

        #endregion

        #region 下拉框改变事件===========================
        protected void ddlISdraw_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.EmployeeNumber__c = txtEmployeeNumber__c.Text;
            this.Region__c = txtRegion__c.Text;
            this.Area__c = txtArea__c.Text;
            this.Name__c = txtName__c.Text;
            this.IsActive__c = ddlISdraw.SelectedValue.ToLower(); ;
            Response.Redirect(searchURL);
        }
        #endregion

        #region 绑定列表=================================
        private void RptBind()
        {
            this.page = DTRequest.GetQueryInt("page", 1);

            //获取数据源
            if (!EmployeeNumber__c.IsNullOrEmpty())
            {
                this.txtEmployeeNumber__c.Text = EmployeeNumber__c;
            }
            if (!Region__c.IsNullOrEmpty())
            {
                this.txtRegion__c.Text = Region__c;
            }
            if (!Area__c.IsNullOrEmpty())
            {
                this.txtArea__c.Text = Area__c;
            }
            if (!Name__c.IsNullOrEmpty())
            {
                this.txtName__c.Text = Name__c;
            }
            if (!IsActive__c.IsNullOrEmpty())
            {
                if (IsActive__c == "true" || IsActive__c == "false")
                {
                    this.ddlISdraw.SelectedValue = IsActive__c;
                }
                if (IsActive__c == "所有")
                {
                    IsActive__c = "";
                    this.ddlISdraw.SelectedValue = "所有";
                }                
            }
            else
            {
                IsActive__c ="true";
            }
            this.rptList.DataSource = sfdc_PNRService.Instance.Get_sfdc_PNR_PageSelect(page, pageSize, orderBy, out totalCount,EmployeeNumber__c,Region__c,Area__c,Name__c,IsActive__c);
            this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = ComLib.UrlHelper.Instance.SetUrl(searchURL).AddParam("page", "__id__").GetAddedParamUrl();
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 搜索操作=================================

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.keywords = txtKeywords.Text;
            Response.Redirect(searchURL);
        }

        //关健字查询
        protected void btnDetailedSearch_Click(object sender, EventArgs e)
        {
            //this.keywords = txtKeywords.Text;
            this.EmployeeNumber__c = txtEmployeeNumber__c.Text;
            this.Region__c = txtRegion__c.Text;
            this.Area__c = txtArea__c.Text;
            this.Name__c = txtName__c.Text;
            this.IsActive__c = ddlISdraw.SelectedValue.ToLower();          
            Response.Redirect(searchURL);
        }

        //筛选类别
        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie(pageSizeCookieKey, _pagesize.ToString(), 14400);
                }
            }
            Response.Redirect(searchURL);
        }

        #endregion

        #region 删除操作=================================

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //检查权限
            //ChkAdminLevel("user_list", ShareMarkingEnums.ActionEnum.Delete.ToString());

            int sucCount = 0;
            int errorCount = 0;
            for (int i = 0; i < rptList.Items.Count; i++)
            {
                int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
                CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
                if (cb.Checked)
                {
                    if (sfdc_PNRService.Instance.Delete_Entity(sfdc_PNR._.PNRID == id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }

            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Delete.ToString(), "删除sfdc_PNR" + sucCount + "条，失败" + errorCount + "条");

            JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");
        }

        #endregion

        #region 生成二维码
        public string geturl(string pnrcode)
        {
            var rela = qr_QrCodeRelateService.Instance.Get_SingleEntity_byWhere(
                qr_QrCodeRelate._.IsDelete == false &&
                qr_QrCodeRelate._.qr_Type == 3 && qr_QrCodeRelate._.rel_Code == pnrcode);
            if (rela != null)
            {
                var qrcode = qr_QrCodeService.Instance.Get_SingleEntity_byWhere(qr_QrCode._.scene_id == rela.qr_Scene_ID);
                if (qrcode != null)
                    return qrcode.qrcode_url;
                return "";
            }
            return "";
        }
        #endregion

        #region 导出成Excel表格==================

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            int sucCount = 0;
            int errorCount = 0;
            try
            {
                DataSet ds = new DataSet();

                DataTable table = new DataTable();
                string sql = @"select distinct pnr.Name__c,pnr.EmployeeNumber__c,pnr.Area__c,pnr.Region__c,pnr.IsActive__c,qr.qrcode_url from sfdc_PNR pnr 
                               left join qr_QrCodeRelate rel on pnr.EmployeeNumber__c=rel.rel_Code 
                               left join qr_QrCode qr on rel.qr_Scene_ID=qr.scene_id";
                table = DbSession.Default.FromSql(sql).ToTable();               
                table.TableName = "sfdc_PNR";
                ds.Tables.Add(table);

                ExcelExportProvider provider = ExcelExportConfiguration.Current.ExcelConfigs["pnrinfo"];

                // 导入配置文件验证
                ConfigExportValidate(provider, ds, "pnrinfo");
                string fullPath;
                string templateFile = null;
                if (!string.IsNullOrEmpty(templateFile))
                    fullPath = templateFile;
                else if (!string.IsNullOrEmpty(provider.TemplateFile))
                {
                    HttpContext context = HttpContext.Current;
                    if (context != null)
                    {
                        fullPath = context.Server.MapPath("~/" + provider.TemplateFile);
                    }
                    else
                    {
                        fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, provider.TemplateFile);
                    }
                }
                else
                    throw new Exception("参数excelFile及预设的TemplateFile都为空，无法打开Excel文件");

                ExcelUtilities excelUtils = new ExcelUtilities();
                excelUtils.ExportExcel(Response, string.Format("PNR信息_{0}", DateTime.Now.ToString("yyyy-MM-dd")), ds, "pnrinfo");
                sucCount += 1;
            }
            catch (Exception ex)
            {
                ComLib.LogLib.Log4NetBase.Log(ex.Message + ex.StackTrace);
                JscriptMsg("下载时发生错误请联系管理员！", searchURL, "Error");
            }
            //记录日志
            AddAdminLog(DTEnums.ActionEnum.Export.ToString(), "导出PNR信息" + sucCount + "条，失败" + errorCount + "条");
            JscriptMsg("下载成功" + sucCount + "条，失败" + errorCount + "条！", searchURL, "Success");           
        }

        protected void ConfigExportValidate(ExcelExportProvider provider, DataSet container, string typeName)
        {
            ///验证数据容器中是否存在DataTable
            if (container.Tables.Count == 0) throw new Exception("DataSet对象容器中没有任何DataTable对象!");
            ///验证导入配置中的配置节是否存在
            if (provider == null) throw new Exception(string.Format("配置中不存在类型为:{0}的导入配置项!", typeName));
            ///验证配置节中是否包含至少1个worksheet
            if (provider.Worksheets == null || provider.Worksheets.Count == 0) throw new Exception(string.Format("配置中类型为:{0}的配置节中不包含Worksheet的定义", typeName));
            // 验证数据容器中存在配置节中配置的datatable
            foreach (var worksheet in provider.Worksheets)
            {
                foreach (Area area in worksheet.Areas)
                    if (!container.Tables.Contains(area.DataTable))
                        throw new Exception(string.Format("DataTable中不包含表 {0}", area.DataTable));
            }
        }
        #endregion
    }

}